$(function() {

    $(".form-myt-distribute-delivery-inputBasic").data("formOptions", {
        updateTotalAmount : function() {
            var $form = $(this);

            var $grid = $form.find(".grid-myt-distribute-delivery-inputBasic");
            var userData = {
                "commodity.display" : "合计："
            };
            // 更新表格汇总统计数据

            userData.quantity = $grid.jqGrid('sumColumn', 'quantity');
            userData.taxAmount = $grid.jqGrid('sumColumn', 'taxAmount');
            userData.amount = $grid.jqGrid('sumColumn', 'amount');
            userData.originalAmount = $grid.jqGrid('sumColumn', 'originalAmount');
            userData.discountAmount = $grid.jqGrid('sumColumn', 'discountAmount');

            $grid.jqGrid("footerData", "set", userData, true);

            var chargeLogisticsAmount = Util.parseFloatValDefaultZero($form.find("input[name='chargeLogisticsAmount']"));
            var discountAmount = Util.parseFloatValDefaultZero($form.find("input[name='discountAmount']"))
            var commodityAmount = userData.amount;
            var totalTaxAmount = userData.taxAmount
            var commodityAndTaxAmount = commodityAmount + totalTaxAmount;
            var totalAmount = commodityAndTaxAmount + chargeLogisticsAmount;
            $form.setFormDatas({
                commodityAmount : commodityAmount,
                totalTaxAmount : totalTaxAmount,
                commodityAndTaxAmount : commodityAndTaxAmount,
                discountAmount : userData.discountAmount,
                totalOriginalAmount : userData.originalAmount,
                totalAmount : totalAmount,
                payedAmount : totalAmount
            });
        },
        bindEvents : function() {
            var $form = $(this);
            var $grid = $form.find(".grid-myt-distribute-delivery-inputBasic");

            $form.find("input[name='chargeLogisticsAmount']").keyup(function() {
                $form.data("formOptions").updateTotalAmount.call($form);
            });
            
            function deliveryInfoAutoComplete(agentPartner_id){
                $.get(WEB_ROOT + "/myt/partner/partner!findByPage", "search['EQ_id']="+agentPartner_id, function(data){
                    $form.setFormDatas({
                        'receivePerson' : data.content[0].contactPerson,
                        'mobilePhone' : data.content[0].contactPhone,
                        'deliveryAddr' : data.content[0].address
                    });
                },"json");
            }
            
            $form.find('input[name="agentPartner.display"]').treeselect({
                url : WEB_ROOT + "/myt/partner/partner!treeDatas",
                callback : {
                    onSingleClick : function(event, treeId, treeNode) {
                        $form.setFormDatas({
                            'agentPartner.id' : Util.startWith(treeNode.id, "-") ? "" : treeNode.id,
                            'agentPartner.display' : Util.startWith(treeNode.id, "-") ? "" : treeNode.name
                        }, true);
                        deliveryInfoAutoComplete(treeNode.id);
                    },
                    onClear : function(event) {
                        $form.setFormDatas({
                            'agentPartner.id' : '',
                            'agentPartner.display' : ''
                        }, true);
                    }
                }
            });

            Biz.setupCustomerProfileSelect($form);

            //扫描枪输入处理
            $form.find("input[name='barcode']").barcodeScanSupport({
                onEnter : function() {
                    var code = $(this).val();
                    if (code != '') {
                        var data = Biz.queryCacheCommodityDatas(code);
                        if (data && data.length > 0) {
                            var rowdata = data[0];
                            var ids = $grid.jqGrid('getDataIDs');
                            var targetRowdata = null;
                            var targetRowid = null;
                            $.each(ids, function(i, id) {
                                var item = $grid.jqGrid('getRowData', id);
                                if (item['commodity.barcode'] == rowdata['barcode']) {
                                    if (item['gift'] != 'true') {
                                        targetRowid = id;
                                        targetRowdata = item;
                                        return false;
                                    }
                                }
                            });

                            if (targetRowdata) {
                                targetRowdata.quantity = Number(targetRowdata.quantity) + 1;
                                $grid.data("gridOptions").calcRowAmount.call($grid, targetRowdata);
                                $grid.jqGrid('setRowData', targetRowid, targetRowdata);
                            } else {

                                var newdata = {
                                    'commodity.id' : rowdata.id,
                                    'commodity.barcode' : rowdata.barcode,
                                    'measureUnit' : rowdata.measureUnit,
                                    'storageLocation.id' : rowdata['defaultStorageLocation.id'],
                                    'commodity.display' : rowdata.display,
                                    'discountRate' : 0,
                                    'taxRate' : 0,
                                    'quantity' : 1
                                }
                                newdata['price'] = rowdata['lastSalePrice'];
                                $grid.data("gridOptions").calcRowAmount.call($grid, newdata);
                                $grid.jqGrid('insertNewRowdata', newdata);
                            }
                            $form.data("formOptions").updateTotalAmount.call($form);
                        }
                        $(this).focus();
                    }
                }
            });

            // 从销售订单选取
            $form.find(".btn-select-sale-order").click(function() {
                $(this).popupDialog({
                    url : WEB_ROOT + '/myt/partner/distribute-delivery!forward?_to_=selectBoxOrderDetails',
                    title : '选取销售订单',
                    callback : function(data) {
                        var master = data.master;
                        var rows = data.rows;

                        $form.setFormDatas({
                            'receivePerson' : master['boxOrder.receivePerson'],
                            'mobilePhone' : master['boxOrder.mobilePhone'],
                            'postCode' : master['boxOrder.postCode'],
                            'title' : "[" + master['reserveDeliveryTime'].substr(0, 7) + "]" + master['boxOrder.title'],
                            'deliveryAddr' : master['boxOrder.deliveryAddr'],
                            'customerProfile.id' : master['boxOrder.customerProfile.id'],
                            'customerProfile.display' : master['boxOrder.customerProfile.display'],
                            'referenceVoucher' : master['boxOrder.orderSeq'],
                            'referenceSource' : 'MYT',
                            'memo' : master['boxOrder.customerMemo']
                        }, false);

                        $.each(rows, function(i, row) {

                            row['storageLocation.id'] = row['defaultStorageLocation.id'] ? row['defaultStorageLocation.id'] : row['commodity.defaultStorageLocation.id'];
                            row['measureUnit'] = row['commodity.measureUnit'];
                            row['boxOrderDetailCommodity.id'] = row['id'];
                            if (row['gift'] == 'true') {
                                row['discountRate'] = 100;
                                row['price'] = 0;
                            } else {
                                row['discountRate'] = 0;
                            }

                            row['taxRate'] = 0;
                            $grid.data("gridOptions").calcRowAmount.call($grid, row);
                            $grid.jqGrid('insertNewRowdata', row);
                            $form.data("formOptions").updateTotalAmount.call($form);
                        });

                        if (master['boxOrder.customerProfile.id']) {
                            Grid.initGrid($form.find(".grid-myt-sd-customer-pay-notify-history"), {
                                url : WEB_ROOT + "/myt/finance/pay-notify-history!findByPage",
                                postData : {
                                    "search['EQ_customerProfile.id']" : master['boxOrder.customerProfile.id']
                                },
                                colModel : [ {
                                    label : '付款时间',
                                    name : 'createdDate',
                                    sortable : false,
                                    width : 120
                                }, {
                                    label : '交易号',
                                    name : 'tradeNo',
                                    sortable : false,
                                    width : 120
                                }, {
                                    label : '总支付额',
                                    name : 'totalFee',
                                    width : 40,
                                    sortable : false,
                                    align : 'right'
                                }, {
                                    label : '支付状态',
                                    name : 'processStatus',
                                    width : 40,
                                    sortable : false,
                                    align : 'center'
                                } ],
                                sortname : 'createdDate',
                                sortorder : 'desc',
                                rowNum : 5,
                                height : 100,
                                pager : false,
                                toppager : false,
                                filterToolbar : false,
                                multiselect : false
                            })
                        }
                    }
                })
            });

            //按金额自动分摊折扣金额
            $form.find(".btn-discount-by-amount").click(function() {
                if ($grid.jqGrid("isEditingMode", true)) {
                    return false;
                }
                //按照“原价金额”的比率计算更新每个行项的折扣额，注意最后一条记录需要以减法计算以修正小数精度问题
                var discountAmount = $form.find("input[name='discountAmount']").val();
                var totalOriginalAmount = $grid.jqGrid('sumColumn', 'originalAmount');
                var perDiscountAmount = MathUtil.mul(MathUtil.div(discountAmount, totalOriginalAmount, 5), 100);
                var lastrowid = null;
                var totalDiscountAmount = 0;
                var ids = $grid.jqGrid("getDataIDs");
                $.each(ids, function(i, id) {
                    var rowdata = $grid.jqGrid("getRowData", id);
                    if (rowdata['gift'] != 'true' && rowdata['commodity.id'] != '') {
                        rowdata['discountRate'] = perDiscountAmount;
                        $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'discountRate');
                        $grid.jqGrid('setRowData', id, rowdata);
                        totalDiscountAmount = MathUtil.add(totalDiscountAmount, rowdata['discountAmount']);
                        lastrowid = id;
                    }
                });
                //最后一条记录需要以减法计算以修正小数精度问题
                if (lastrowid) {
                    var rowdata = $grid.jqGrid("getRowData", lastrowid);
                    rowdata['discountAmount'] = MathUtil.sub(discountAmount, MathUtil.sub(totalDiscountAmount, rowdata['discountAmount']));
                    $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'discountAmount');
                    $grid.jqGrid('setRowData', lastrowid, rowdata);
                }

                $form.data("formOptions").updateTotalAmount.call($form);

            });

            //打印快递单
            $form.find(".btn_express_print_QF").click(function() {
                if (confirm("确认调用票据打印程序打印当前快递单吗?")) {
                    var url = WEB_ROOT + "/rpt/jasper-report!generate?format=XLS&report=EXPRESS_QUANFENG&contentDisposition=attachment";
                    url += "&reportParameters['SALE_DELIVERY_IDS']=" + $form.find("input[name='voucher']").val();
                    window.open(url, "_blank");
                }
            });
            $form.find(".btn_express_print_ST").click(function() {
                if (confirm("确认调用票据打印程序打印当前快递单吗?")) {
                    var url = WEB_ROOT + "/rpt/jasper-report!generate?format=XLS&report=EXPRESS_SHENTONG&contentDisposition=attachment";
                    url += "&reportParameters['SALE_DELIVERY_IDS']=" + $form.find("input[name='voucher']").val();
                    window.open(url, "_blank");
                }
            });
            //打印发货单
            $form.find(".btn_delivery_print").click(function() {
                if (confirm("确认打印发货清单?")) {
                    var url = WEB_ROOT + "/rpt/jasper-report!generate?format=XLS&report=SALE_DELIVERY_COMMODITY_LIST&contentDisposition=attachment";
                    url += "&reportParameters['SALE_DELIVERY_IDS']=" + $form.find("input[name='voucher']").val();
                    window.open(url, "_blank");
                }
            });

            $form.find("input[name='accountSubject.display']").treeselect({
                url : WEB_ROOT + "/myt/finance/account-subject!findPaymentAccountSubjects",
                callback : {
                    onSingleClick : function(event, treeId, treeNode) {
                        $form.setFormDatas({
                            'accountSubject.id' : treeNode.id,
                            'accountSubject.display' : treeNode.display
                        }, true);
                    },
                    onClear : function(event) {
                        $form.setFormDatas({
                            'accountSubject.id' : '',
                            'accountSubject.display' : ''
                        }, true);
                    }
                }
            });
        },
        preValidate : function() {
            var $form = $(this);
            var $payedAmount = $form.find("input[name='payedAmount']");
            var $paymentAccountSubjects = $form.find("input[name='accountSubject.id']");
            if ($payedAmount.val() != '' && $paymentAccountSubjects.val() == '') {
                bootbox.alert("如有收款金额则必须选取收款账户");
                return false;
            }
        }
    });

    $(".grid-myt-distribute-delivery-inputBasic").data("gridOptions", {
        calcRowAmount : function(rowdata, src) {
            rowdata['originalAmount'] = MathUtil.mul(rowdata['price'], rowdata['quantity']);
            if (src == 'discountAmount') {
                rowdata['discountRate'] = MathUtil.div(rowdata['discountAmount'], rowdata['originalAmount'], 5) * 100;
                rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
            } else if (src == 'amount') {
                rowdata['discountAmount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['amount']);
                rowdata['discountRate'] = MathUtil.div(rowdata['discountAmount'], rowdata['originalAmount'], 5) * 100;
            } else {
                rowdata['discountAmount'] = MathUtil.div(MathUtil.mul(rowdata['discountRate'], rowdata['originalAmount']), 100);
                rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
            }

            rowdata['taxAmount'] = MathUtil.div(MathUtil.mul(rowdata['amount'], rowdata['taxRate']), 100);
            rowdata['commodityAndTaxAmount'] = MathUtil.add(rowdata['amount'], rowdata['taxAmount']);
        },
        updateRowAmount : function(src) {
            var $grid = $(this);
            var rowdata = $grid.jqGrid("getEditingRowdata");
            $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, src);
            $grid.jqGrid("setEditingRowdata", rowdata);
        },
        batchEntitiesPrefix : "saleDeliveryDetails",
        url : function() {
            var pk = $(this).attr("data-pk");
            if (pk) {
                return WEB_ROOT + "/myt/partner/distribute-delivery!saleDeliveryDetails?id=" + pk + "&clone=" + $(this).attr("data-clone");
            }
        },
        colModel : [ {
            label : '行项号',
            name : 'subVoucher',
            width : 50
        }, {
            label : '销售（发货）商品',
            name : 'commodity.display',
            width : 200
        }, {
            label : '单位',
            name : 'measureUnit',
            width : 80
        }, {
            label : '数量',
            name : 'quantity',
            width : 80,
            formatter : 'number',
            summaryType : 'sum'
        }, {
            label : '销售单价',
            name : 'price',
            width : 80,
            formatter : 'currency',
            summaryType : 'sum'
        }, {
            label : '是否赠品',
            name : 'gift',
            width : 80,
            edittype : 'checkbox',
            editable : true,
            align : 'center',
            responsive : 'sm'
        }, {
            label : '原始金额',
            name : 'originalAmount',
            width : 80,
            formatter : 'currency',
            responsive : 'sm'
        }, {
            label : '折扣率(%)',
            name : 'discountRate',
            width : 80,
            formatter : 'currency',
            responsive : 'sm'
        }, {
            label : '折扣额',
            name : 'discountAmount',
            width : 80,
            align : 'right',
            responsive : 'sm'
        }, {
            label : '折后金额',
            name : 'amount',
            width : 80,
            formatter : 'currency',
            responsive : 'sm'
        }, {
            label : '税率(%)',
            name : 'taxRate',
            width : 80,
            formatter : 'number',
            hidden : true,
            responsive : 'sm'
        }, {
            label : '税额',
            name : 'taxAmount',
            width : 80,
            formatter : 'currency',
            hidden : true,
            responsive : 'sm'
        }, {
            label : '含税总金额',
            name : 'commodityAndTaxAmount',
            width : 80,
            formatter : 'currency',
            hidden : true,
            responsive : 'sm'
        }, {
            label : '发货仓库',
            name : 'storageLocation.id',
            width : 150,
            editable : true,
            editrules : {
                required : true
            },
            stype : 'select',
            searchoptions : {
                value : Biz.getStockDatas()
            }
        }, {
            label : '批次号',
            name : 'batchNo',
            width : 80
        }, {
            label : '批次过期日期',
            name : 'expireDate',
            width : 80
        } ],
        footerrow : true,
        beforeInlineSaveRow : function(rowid) {
            var $grid = $(this);
            $grid.data("gridOptions").updateRowAmount.call($grid);
        },
        afterInlineSaveRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        afterInlineDeleteRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        userDataOnFooter : true
    });

});
